using UnityEngine;
using UnityEngine.UI;
using _00_Source.__naptime;

namespace RewiredConsts.__Naptime
{
	[RequireComponent(typeof(Image))]
	public sealed class DynamicIconChanger : MonoBehaviour
	{
		[SerializeField]
		private bool overrideIcons;

		[SerializeField]
		private string iconId;

		[SerializeField]
		private ChangeableIconChunk changeableIconChunk;

		private Image _image;

		private void Awake()
		{
			DynamicIconObserver.OnLastDeviceChanged += OnLastDeviceChanged;
			_image = GetComponent<Image>();
			OnLastDeviceChanged(DynamicIconObserver.ConsoleBinding);
		}

		private void OnDestroy()
		{
			DynamicIconObserver.OnLastDeviceChanged -= OnLastDeviceChanged;
		}

		private void OnLastDeviceChanged(ConsoleBinding consoleBinding)
		{
			DynamicIconChangerConfig service;
			if (overrideIcons)
			{
				Sprite sprite = consoleBinding switch
				{
					ConsoleBinding.PS => changeableIconChunk.playStationIcon, 
					ConsoleBinding.Nintendo => changeableIconChunk.nintendoIcon, 
					ConsoleBinding.NintendoSingleJoyCon => (changeableIconChunk.nintendoSingleJoyConIcon != null) ? changeableIconChunk.nintendoSingleJoyConIcon : changeableIconChunk.nintendoIcon, 
					ConsoleBinding.Xbox => changeableIconChunk.xboxIcon, 
					ConsoleBinding.SteamDeck => changeableIconChunk.steamDeck, 
					_ => changeableIconChunk.pcIcon, 
				};
				_image.preserveAspect = true;
				_image.sprite = sprite;
			}
			else if (ScriptableObjectService.IsInit && ScriptableObjectService.Instance.TryGetService<DynamicIconChangerConfig>(out service))
			{
				ChangeableIconChunk icons = service.GetIcons(iconId);
				Sprite sprite = consoleBinding switch
				{
					ConsoleBinding.PS => icons.playStationIcon, 
					ConsoleBinding.Nintendo => icons.nintendoIcon, 
					ConsoleBinding.Xbox => icons.xboxIcon, 
					ConsoleBinding.SteamDeck => icons.steamDeck, 
					_ => icons.pcIcon, 
				};
				bool flag = sprite != null;
				_image.preserveAspect = true;
				_image.sprite = sprite;
				_image.enabled = flag;
			}
		}
	}
}
